package cn.itcast.bos.web.action.common;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;


@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

	protected T model;
	
	@Override
	public T getModel() {
		return model;
	}

	//泛型转换
	public BaseAction() {
		Type genericSuperclass = this.getClass().getGenericSuperclass();
		ParameterizedType parameterizedType=(ParameterizedType) genericSuperclass;
		Class entityClass=(Class) parameterizedType.getActualTypeArguments()[0];
		try {
			model =  (T) entityClass.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			System.out.println("模型构造失败!!");
		}
	}
	// 接收分页查询参数
		protected int page;
		protected int rows;

		public void setPage(int page) {
			this.page = page;
		}

		public void setRows(int rows) {
			this.rows = rows;
		}
		// 将分页查询结果数据，压入值栈的方法
		protected void pushPageDataToValueStack(Page<T> pageData) {
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("total", pageData.getTotalElements());
			result.put("rows", pageData.getContent());

			ActionContext.getContext().getValueStack().push(result);
		}
	
	
	
}
